-module(handle_code_block).
-include_lib("nitrogen/include/wf.inc").
-compile(export_all).

%MUST be used with an "interpreter_block" block on the page (for the time being)
%And with a "open_code_block"

						%Builders
assemble_header(X) ->
    X.

assemble_menu(X) ->
    Body =  [
	     #p{},
	     #rounded_panel{color=gray, body=[
					      #inplace_textbox{id = hcb_name, class="hcb_button", text="Entrez un nom"},
					      #hr{},
					      #button{id = hcb_new, class="hcb_button", text="Nouveau code", actions=helper:act(?MODULE, new)},
					      #br{},
					      #button{id = hcb_open, class="hcb_button", text="Ouvrir un code", actions=helper:act(?MODULE, open)},
					      #hr{},
					      #button{id = hcb_save, class="hcb_button", text="Sauvegarder", actions=helper:act(?MODULE, save)},
					      #br{},
					      #button{id = hcb_newrev, class="hcb_button", text="Créer une révision", actions=helper:act(?MODULE, newrev)}
					     ], style="width: 100%;"} 
	    ],
    case hglobals:vget(helper:id_me(), connected) of
	true ->
	    X ++ Body;
	_ ->
	    X
    end.

assemble_body(X) ->
    X.
						%Wiring

wire() ->
    wf:wire(hcb_open, #event{target=ocb_openbox, actions=#show{}}), %==> open_code_block
    ok.
						%Behavior
behave(_) ->
    ok.
						%Events

%This uses hard coded names from the interpreter block

event(new) ->   
    hglobals:vput(helper:id_me(), hcb_code_isnew, true),

    wf:update(ib_code, #textarea{id=ib_code, class="ib_code"}),
    wf:update(ib_placement,#table {id=ib_placement, class="ib_table", rows=[#tablerow { cells=[ #tablecell { id=ib_output }]}]} ),
    wf:update(hcb_name, #inplace_textbox{id = hcb_name, class="hcb_button", text="Entrez un nom"}),

    ok;
event(open) ->
%%     wf:wire( #lightbox { id=lightbox1, body=[
%%      #panel { body=[
%% 		    "test"
%%      ]}
%% ]}),
    ok;

event(save) ->
    case hglobals:vget(helper:id_me(), hcb_code_isnew) of
	true ->
	    hglobals:vput(helper:id_me(), hcb_code_isnew, false),
	    case hglobals:vget(helper:id_me(), hcb_code_name) of
		not_found -> 
		    wf:wire(#alert{text="Merci d'enter un nom pour votre code"});
		Name -> 
		    [Code] = wf:q(ib_code),

		    {ok, CID} = db:add(code, {Name, db:name_to_id(member, wf:user() )}),
		    {ok, RID} = db:add(revision, {"", false, Code}),
		    db:bind(CID, RID),

		    hglobals:vput(helper:id_me(), hcb_code_id, CID),
		    hglobals:vput(helper:id_me(), hcb_rev_id, RID),
		    ok
	    end;
	_ ->
	    [Code] = wf:q(ib_code),
	    db:modify_code(hglobals:vget(helper:id_me(), hcb_rev_id), Code)
    end;

event(_) ->
    ok.
